package com.example.educationai.service.impl;

import com.example.educationai.entity.ExamRecord;
import com.example.educationai.entity.Exam;
import com.example.educationai.entity.SimpleUser;
import com.example.educationai.repository.ExamRecordRepository;
import com.example.educationai.service.ExamRecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.web.client.RestTemplate;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.util.HashMap;
import java.util.Map;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.UUID;
import java.util.Base64;

@Service
public class ExamRecordServiceImpl implements ExamRecordService {
    private static final Logger log = LoggerFactory.getLogger(ExamRecordServiceImpl.class);

    @Autowired
    private ExamRecordRepository examRecordRepository;

    @Value("${app.upload.path}")
    private String uploadPath;

    @Value("${app.ai.api.url}")
    private String aiApiUrl;

    @Value("${app.ai.api.key}")
    private String aiApiKey;

    @Override
    public ExamRecord save(ExamRecord record) {
        log.debug("保存考试记录: {}", record);
        return examRecordRepository.save(record);
    }

    @Override
    public ExamRecord createRecord(ExamRecord record, MultipartFile examImage) {
        try {
            log.debug("开始创建考试记录，文件大小: {}", examImage.getSize());
            if (examImage == null || examImage.isEmpty()) {
                throw new RuntimeException("试卷图片不能为空");
            }
            
            // 设置考试记录状态
            record.setStatus("PENDING");
            
            // 保存图片数据
            byte[] imageData = examImage.getBytes();
            log.debug("图片数据大小: {} bytes", imageData.length);
            record.setExamImage(imageData);
            
            // 保存记录
            ExamRecord savedRecord = save(record);
            log.debug("考试记录创建成功: {}", savedRecord.getId());
            
            return savedRecord;
        } catch (Exception e) {
            log.error("创建考试记录失败", e);
            throw new RuntimeException("创建考试记录失败: " + e.getMessage(), e);
        }
    }

    @Override
    public ExamRecord updateRecord(ExamRecord record) {
        return save(record);
    }

    @Override
    public void deleteRecord(Long id) {
        examRecordRepository.deleteById(id);
    }

    @Override
    public ExamRecord getRecord(Long id) {
        return examRecordRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("未找到考试记录: " + id));
    }

    @Override
    public List<ExamRecord> getExamRecords(Exam exam) {
        return examRecordRepository.findByExam(exam);
    }

    @Override
    public ExamRecord gradeRecord(Long id, Double score, String comments) {
        ExamRecord record = getRecord(id);
        record.setScore(score);
        record.setComments(comments);
        record.setStatus("GRADED");
        return save(record);
    }

    @Override
    public void gradeExam(ExamRecord record) {
        try {
            log.debug("开始AI批改考试记录: {}", record.getId());
            
            // 准备请求数据
            Map<String, Object> requestData = new HashMap<>();
            requestData.put("examImage", Base64.getEncoder().encodeToString(record.getExamImage()));
            requestData.put("answerRequirements", record.getAnswerRequirements());
            
            // 设置请求头
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            headers.set("Authorization", "Bearer " + aiApiKey);
            
            // 发送请求到AI服务
            RestTemplate restTemplate = new RestTemplate();
            HttpEntity<Map<String, Object>> request = new HttpEntity<>(requestData, headers);
            
            Map<String, Object> response = restTemplate.postForObject(
                aiApiUrl + "/grade",
                request,
                Map.class
            );
            
            // 处理AI返回的结果
            if (response != null) {
                Double score = Double.parseDouble(response.get("score").toString());
                String comments = response.get("comments").toString();
                
                // 更新考试记录
                record.setScore(score);
                record.setComments(comments);
                record.setStatus("GRADED");
                
                // 保存更新后的记录
                save(record);
                
                log.debug("AI批改完成，分数: {}, 评语: {}", score, comments);
            } else {
                throw new RuntimeException("AI服务返回结果为空");
            }
        } catch (Exception e) {
            log.error("AI批改失败", e);
            throw new RuntimeException("AI批改失败: " + e.getMessage());
        }
    }

    @Override
    public List<ExamRecord> getUserRecords(SimpleUser user) {
        if (SimpleUser.UserRole.TEACHER.equals(user.getRole())) {
            return examRecordRepository.findByTeacher(user);
        } else {
            return examRecordRepository.findByStudentName(user.getUsername());
        }
    }

    private String saveImage(MultipartFile file) throws IOException {
        // 确保上传目录存在
        Path uploadDir = Paths.get(uploadPath);
        if (!Files.exists(uploadDir)) {
            Files.createDirectories(uploadDir);
        }

        // 生成唯一文件名
        String originalFilename = file.getOriginalFilename();
        String extension = originalFilename.substring(originalFilename.lastIndexOf("."));
        String filename = UUID.randomUUID().toString() + extension;

        // 保存文件
        Path filePath = uploadDir.resolve(filename);
        Files.copy(file.getInputStream(), filePath);

        return filename;
    }
} 